package com.op.filter;

import com.alibaba.fastjson.JSONObject;
import com.op.constants.JWTConstant;
import com.op.response.ResponseResult;
import com.op.response.StateCode;
import com.op.service.JWTService;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName： JWTFilter
 * Date： 2021/10/13 22:28
 *
 * @author 孤焰
 * @version 1.0
 **/

@WebFilter(urlPatterns = "*", filterName = JWTConstant.FILTER_NAME)
@Order(0)
public class JWTFilter implements Filter {
    @Resource
    JWTService jwtService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        // 如果不是Http请求直接通过
        if (!(servletRequest instanceof HttpServletRequest)
                || JWTConstant.OPTIONS_METHOD.equals(httpServletRequest.getMethod())
                || JWTConstant.LOGIN_URI.equals(httpServletRequest.getRequestURI())
                || JWTConstant.GET_ROLES.equals(httpServletRequest.getRequestURI())
                || JWTConstant.USER_CHECK.equals(httpServletRequest.getRequestURI())
                || JWTConstant.USER_REGISTERED.equals(httpServletRequest.getRequestURI())
                || JWTConstant.USER_TEMP_ACCOUNT.equals(httpServletRequest.getRequestURI())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 获取并解析token
        try {
            jwtService.deCode(httpServletRequest.getHeader(JWTConstant.AUTHORIZATION_REQUEST_HEADER));
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            // 解析token失败
            e.printStackTrace();
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.setContentType(JWTConstant.CONTENT_TYPE);
            httpServletResponse.setHeader(JWTConstant.CORS_RESPONSE_HEADER, "*");
            httpServletResponse.getWriter()
                    .write(JSONObject.toJSONString(ResponseResult.fail(StateCode.UN_AUTHORIZATION)));
        }
    }
}
